import React from 'react';
import { inject, observer } from 'mobx-react';
import * as mobx from 'mobx';
import './index.less';
import { getAntd, getEcCom, getLabel } from '../../../util/convert';

@inject('selectNextFlowStore')
@observer
export default class Main extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            nextNodeIds: [],
        };
    }

    componentDidMount() {
        const { selectNextFlowStore } = this.props;
        // selectNextFlowStore.getNodeInfo();
        if(selectNextFlowStore.nextNodeIds != '') {
            this.setState({ nextNodeIds: selectNextFlowStore.nextNodeIds.split(',') });
        }
    }

    render() {
        const { Button, message } = getAntd();
        const { WeaTable, WeaSearchGroup, WeaHelpfulTip, WeaDialogFooter, WeaRightMenu, WeaFormItem, WeaSelect, WeaBrowser, WeaPopoverHrm } = getEcCom();
        const { selectNextFlowStore } = this.props;
        const { nodeInfo = [] } = selectNextFlowStore;
        return (
            <div className="wf-select-node-choose">
                <div className="wf-select-node-choose-content">
                    <WeaRightMenu {...this.getMoreBtns()}>
                    {
                        nodeInfo.length > 0 && this.renderNodeTable()
                    }
                    </WeaRightMenu>
                </div>
                <WeaDialogFooter buttons={this.getButtons()} moreBtn={this.getMoreBtns()} />
                <WeaPopoverHrm />
            </div>
        );
    }
    renderNodeTable() {
        const { Button, message } = getAntd();
        const { WeaTable, WeaSearchGroup, WeaHelpfulTip, WeaDialogFooter, WeaRightMenu, WeaFormItem, WeaSelect, WeaBrowser, WeaPopoverHrm } = getEcCom();
        const { selectNextFlowStore } = this.props;
        const { nodeInfo, showAllNodeOperators, setShowAllNodeOperators, nextNodeInfo, nodeAttribute } = selectNextFlowStore;
        let columns = [
            {
                title: <span>{getLabel(15070, '节点名称')}</span>,
                key: 'nodeName',
                dataIndex: 'nodeName',
                width: '45%',
            },
            {
                title: <span>{getLabel(99, '操作者')}</span>,
                key: 'operator',
                dataIndex: 'operator',
                width: '55%',
            },
        ];
        let datas = [];
        nodeInfo && nodeInfo.map((item) => {
            let row = mobx.toJS(item);
            // let operators = row.operator;
            let operators = item.operators;
            let show = showAllNodeOperators[row.id];
            row = { ...row,
                operator: operators && operators.length > 0 ?
                this.getOperatorCom(operators, show, () => {
                    setShowAllNodeOperators(row.id);
                }) : row.operatorGroupStr,
            };
            datas.push(row);
        });
        const that = this;
        let rowSelection = {
            type: 'radio',
            selectedRowKeys: this.state.nextNodeIds,
            onChange(selectedRowKeys, selectedRows) {
                that.setState({ nextNodeIds: selectedRowKeys });
            },
        };
        // 当前节点为分叉中间点，显示节点属性，列表为多选
        if (nodeAttribute == '1') {
            columns = [
                {
                    title: <span>{getLabel(15070, '节点名称')}</span>,
                    key: 'nodeName',
                    dataIndex: 'nodeName',
                    width: '30%',
                },
                {
                    title: <span>{getLabel(21393, '节点属性')}</span>,
                    key: 'nodeAttributeName',
                    dataIndex: 'nodeAttributeName',
                    width: '20%',
                },
                {
                    title: <span>{getLabel(99, '操作者')}</span>,
                    key: 'operator',
                    dataIndex: 'operator',
                    width: '50%',
                },
            ];
            rowSelection.type = 'checkbox';
        }
        return (
            <WeaTable
              columns={columns}
              dataSource={datas}
              rowSelection={rowSelection}
              pagination={false}
            />
        );
    }

    getButtons() {
        const { Button, message } = getAntd();
        const { WeaTable, WeaSearchGroup, WeaHelpfulTip, WeaDialogFooter, WeaRightMenu, WeaFormItem, WeaSelect, WeaBrowser, WeaPopoverHrm } = getEcCom();
        let buttons = [];
        buttons.push(<Button type="primary" onClick={this.doConfirm}>{getLabel(83446, '确定')}</Button>);
        return buttons;
    }
    getMoreBtns() {
        let btns = [];
        btns.push({
            key: '0',
            icon: <i className="icon-coms-Preservation" />,
            content: getLabel(83446, '确定'),
            onClick: key => this.doConfirm(),
        });
        return { datas: btns };
    }
    doConfirm = () => {
        const { selectNextFlowStore } = this.props;
        const { nodeInfoConfirmEvent, appendNextNodeInfo, updateFormByNodeInfo, setNextNodeIds } = selectNextFlowStore;

        if(this.checkSelectedNodes(this.state.nextNodeIds)) {
            setNextNodeIds(this.state.nextNodeIds.join(','));
            updateFormByNodeInfo();
            nodeInfoConfirmEvent();
        }
    }

    // 检查选择的节点类型
    checkSelectedNodes(checkNodeIds) {
        const { selectNextFlowStore } = this.props;
        const { Modal } = getAntd();
        const { nodeInfoMap, branchNodesMap } = selectNextFlowStore;
        if (checkNodeIds.length > 1) {
            let isAllTrunkNode = true;//是否全是主干节点
            let isAllDiffBranchNode = true;//是否全为不同分支分叉中间点
            let branchMarks = [];
            checkNodeIds.map((nodeid) => {
                //为主干节点
                if (nodeInfoMap[nodeid] && nodeInfoMap[nodeid].nodeAttribute != '2') {
                    isAllDiffBranchNode = false;
                } else {
                    //分叉中间点
                    isAllTrunkNode = false;

                    Object.keys(branchNodesMap).map(key => {
                        if(branchNodesMap[key].indexOf(nodeid) > -1) {
                            if(branchMarks.indexOf(key) > -1) {//节点在相同的分支
                                isAllDiffBranchNode = false;
                            } else {//记录分支标识
                                branchMarks.push(key);
                            }
                        }
                    })
                }
            });

            //选择的节点全为主干节点，且选择了多个
            if(isAllTrunkNode) {
                Modal.warning({
                    content: getLabel(525840,"非分叉中间点只能选择一个"),
                    okText:getLabel(83446,"确定"),
                    onOk() {
                    },
                });
                return false;
            }

            //不全为不同分支分叉中间点
            if(!isAllDiffBranchNode) {
                Modal.warning({
                    content: getLabel(525841,"选择的多个节点必须为不同分支的分叉中间点"),
                    okText:getLabel(83446,"确定"),
                    onOk() {
                    },
                });
                return false;
            }
        }
        return true;
    }

    // 渲染操作者列
    getOperatorCom(operators = [], show, func) {
        let showList = (operators.length <= 5 || show) ? operators : operators.slice(0, 5);
        let operatorLink = [];
        for (let i = 0; i < showList.length; i++) {
            let operatorItem = showList[i];
            if (operatorItem.agent) { // 存在代理
                operatorLink.push(<span style={{marginRight : '10px'}}><a href={`javaScript:openhrm(${operatorItem.id});`} onClick={(e) => { window.pointerXY(e); }} title={operatorItem.name} >{operatorItem.name}</a>-><a href={`javaScript:openhrm(${operatorItem.agent.id});`} onClick={(e) => { window.pointerXY(e); }} title={operatorItem.agent.name} >{operatorItem.agent.name}</a><span /></span>);
            } else {
                operatorLink.push(<span style={{marginRight : '10px'}}><a href={`javaScript:openhrm(${operatorItem.id});`} onClick={(e) => { window.pointerXY(e); }} title={operatorItem.name} >{operatorItem.name}</a><span /></span>);
            }
        }
        return (
            <div className="operators">
                    <div className="browserDiv">
                        {/* <WeaBrowser type="17" isSingle={false} replaceDatas={showList} viewAttr="1"></WeaBrowser> */}
                        {operatorLink}
                    </div>
                    {operators.length >= 6 &&
                        <span
                          className="iconSpan"
                          title={show ? getLabel(26985, '收起') : getLabel(20234, '显示全部')}
                          onClick={() => {
                                func && func();
                            }}
                        >
                            <em className={show ? 'icon-coms-up' : 'icon-coms-down'} />
                        </span>
                    }
            </div>
        );
    }
}
